# -*- encoding:utf-8 -*-
# @time: 2023/4/5 15:42
# @author: Maxs_hu
from django import forms
from django.shortcuts import redirect
from django.shortcuts import render
from django.urls import reverse
from django.http import JsonResponse

from web import models
from utils.response import baseResponse


def policy_list(request):
    queryset = models.PricePolicy.objects.all()
    return render(request, 'policy_list.html', {'queryset': queryset})


class addModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 添加bootstrap样式
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'

    class Meta:
        model = models.PricePolicy  # 导入数据库相关信息
        fields = ['count', 'price']
        widgets = {
            'count': forms.TextInput(attrs={"placeholder": '请输入个数'}),
            'price': forms.TextInput(attrs={"placeholder": '请输入价格'})
        }
        error_messages = {
            'count': {
                'required': "请填写个数",
                'invalid': "格式不正确",
            },
            'price': {
                'required': "请填写价格",
                'invalid': "格式不正确",
            },
        }


def policy_add(request):
    if request.method == 'GET':
        form = addModelForm()
        return render(request, 'policy_add.html', {'form': form})
    form = addModelForm(data=request.POST)
    if not form.is_valid():
        return render(request, 'policy_add.html', {'form': form})
    form.save()  # 保存数据
    return redirect(reverse('policy_list'))


class editModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'

    class Meta:
        model = models.PricePolicy
        fields = ['count', 'price']
        widgets = {
            'count': forms.TextInput(attrs={'placeholder': '请输入个数'}),
            'price': forms.TextInput(attrs={'placeholder': '请输入价格'})
        }
        error_message = {
            'count': {
                'required': "请输入个数",
                'invalid': '格式不正确'
            },
            'price': {
                'required': "请输入价格",
                'invalid': '格式不正确'
            }
        }


def policy_edit(request, pk):
    instance = models.PricePolicy.objects.filter(id=pk).first()
    if request.method == 'GET':
        form = editModelForm(instance=instance)  # 传入初始数据
        return render(request, 'policy_edit.html', {'form': form})

    form = editModelForm(data=request.POST, instance=instance)  # 添加初始数据, 后面才会更改
    if not form.is_valid():
        return render(request, 'policy_edit.html', {'form': form})

    form.save()  # 保存已经修改的值

    return redirect(reverse('policy_list'))


def policy_delete(request):
    obj = baseResponse()
    if request.method == 'GET':
        try:
            nid = request.GET.get('nid')
            models.PricePolicy.objects.filter(id=nid).delete()  # 删除数据
        except Exception as e:
            obj.status = False
            obj.detail = '出错了. 请联系管理员'
        return JsonResponse(obj.dict, json_dumps_params={'ensure_ascii': False})
